package com.can.core.advice;

import com.alibaba.fastjson.JSONException;
import com.can.common.constant.JsonResultEnum;
import com.can.entityDTO.JsonResult;
import com.can.common.exception.ServiceException;
import com.can.common.exception.UserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Desription 后台统一异常处理类
 * @Author can
 * @Date 2018/9/29
 * @Version 1.0
 */
@ControllerAdvice
public class WebControllerAdvice {
    private final static Logger logger = LoggerFactory.getLogger(ValidateControllerAdvice.class);

    /**
     * 用户模块处理类
     */
    @ExceptionHandler(UserException.class)
    @ResponseBody
    //返回的状态码
    public JsonResult handlerAuthenticationException(UserException ex){
        logger.error(ex.getMessage(),ex);
        return JsonResult.createError(ex.getMessage());
    }

    /**
     * service异常处理类
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    //返回的状态码
    public JsonResult handlerServiceException(ServiceException ex){
        logger.error(ex.getMessage(),ex);
        return JsonResult.createError(ex.getMessage());
    }

    /**
     * 前端参数请求处理类
     */
    @ExceptionHandler(NumberFormatException.class)
    @ResponseBody
    //返回的状态码
    public JsonResult handlerNumberFormatException(NumberFormatException ex){
        logger.error(ex.getMessage(),ex);
        if(ex.getMessage().startsWith("For input")){
           return new JsonResult(JsonResultEnum.VALIDATE_PARAM_ERROR, "请求参数类型错误!");
        }
        return JsonResult.createError("参数类型转换错误!");
    }

    /**
     * 前端参数请求处理类
     */
    @ExceptionHandler(JSONException.class)
    @ResponseBody
    //返回的状态码
    public JsonResult handlerJSONException(JSONException ex){
        logger.error(ex.getMessage(),ex);
        if(ex.getMessage().contains("error, field")){
            return new JsonResult(JsonResultEnum.VALIDATE_PARAM_ERROR, "请求参数类型错误!");
        }
        return JsonResult.createError("参数类型转换错误!");
    }
}
